import os
import datetime
import requests
import datetime
import json


from django.shortcuts import render, redirect
from django.http import HttpResponseRedirect
from django.contrib.auth.models import User
from django.contrib import auth
from .models import MyUser
from blog.models import Blog
from teach.models import Item
from service.models import Lesson_note, Scheduling
from django.utils import timezone
from django.db.models import Q
from teachzero import settings
# from home.homeform import CreateBugForm
from django.views.decorators.csrf import csrf_exempt  # 用装饰器跳过保护
from django.contrib.auth.decorators import login_required


# Create your views here.

def user_check(request):
    """用户登陆检查"""
    context = {
        "title": settings.TITLE,
        "welcoming": settings.WELCOMING,
    }
    if request.user.is_authenticated:
        context["username"] = request.user.username
        myuser = MyUser.objects.filter(user=request.user)
        if myuser:
            myuser = myuser[0]
        else:
            myuser = MyUser.objects.create(user=request.user)
            myuser.save()
        context["myuser"] = myuser
    if request.user.is_staff:  # 如果是工作人员
        context["superuser"] = request.user.username
    return context


def get_bing():
    """
    bing接口
    """
    requests.adapters.DEFAULT_RETRIES = 5  # 增加重连次数
    s = requests.session()
    s.keep_alive = False  # 关闭多余连接
    req = s.get(
        "http://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1")
    data = req.json()
    bing_url = "http://cn.bing.com" + data["images"][0]["url"]
    bing_title = data["images"][0]["title"]
    return [bing_url, bing_title]


def index(request, messages={}):
    """
    网站主页
    """
    context = user_check(request)
    for key in messages:
        context[key] = messages[key]
    path = os.path.abspath(__file__)
    path = os.path.dirname(path)
    path = os.path.dirname(path)
    path = os.path.dirname(path)
    date = datetime.datetime.today()
    date = f"{date.year}-{date.month}-{date.day}"
    pic_data_path = os.path.join(path, "statics", "home", "pics.json")
    try:
        if not os.path.isfile(pic_data_path):
            bing_url, bing_title = get_bing()
            pic_dict = {
                date: [bing_url, bing_title],
            }
            with open(pic_data_path, "w") as f:
                json.dump(pic_dict, f, ensure_ascii=False, indent=2)
        else:
            with open(pic_data_path, "r") as f:
                pic_dict = json.load(f)
                if date in pic_dict:
                    bing_url, bing_title = pic_dict[date]
                else:
                    bing_url, bing_title = get_bing()
                    pic_dict[date] = [bing_url, bing_title]
                    with open(pic_data_path, "w") as f:
                        json.dump(pic_dict, f, ensure_ascii=False, indent=2)
    except:
        bing_url = "http://cn.bing.com/th?id=OHR.GroundhogThree_ZH-CN6720558481_1920x1080.jpg&rf=LaDigue_1920x1080.jpg&pid=hp"
        bing_title = "春天来了"

    blogs = Blog.objects.all()
    blogs = sorted(blogs, key=lambda x: (
        x.modified_time, x.modified_time))  # 按更新时间排序
    blogs = blogs[-3::]
    blogs = blogs[::-1]
    lessons = Item.objects.all()
    lessons = sorted(lessons, key=lambda x: (
        x.modified_time, x.modified_time))  # 按更新时间排序
    lessons = lessons[-3::]
    lessons = lessons[::-1]
    context["bing_url"] = bing_url
    context["bing_title"] = bing_title
    context['blogs'] = blogs
    context['lessons'] = lessons
    return render(request, "home/index.html", context)


def dashboard(request):
    """
    后台管理
    """
    context = user_check(request)
    context["blog_count"] = len(Blog.objects.all())
    context["user_count"] = len(User.objects.all())
    context["lesson_count"] = len(Item.objects.filter(func_type="lesson"))
    context["training_count"] = len(Item.objects.filter(func_type="training"))
    context["title"] += "-后台管理"
    now = timezone.localtime()
    day_num = now.isoweekday()
    # 计算当前日期所在周一
    monday = (now - timezone.timedelta(days=day_num-1, hours=now.hour,
                                       minutes=now.minute, seconds=now.second))
    sunday = monday+timezone.timedelta(days=7)

    # 计算次数
    today = {"plan": 0, "students_p": 0, "already": 0, "students_a": 0}
    week = {"plan": 0, "students_p": 0, "already": 0, "students_a": 0}
    month_ = {"plan": 0, "students_p": 0, "already": 0, "students_a": 0}
    for i in Scheduling.objects.all():
        if i.start.date() == now.date():
            today["students_p"] += i.user.count()
            today["plan"] += 1
        if i.start >= monday and i.start <= sunday:
            week["students_p"] += i.user.count()
            week["plan"] += 1
        if i.start.year == now.year and i.start.month == now.month:
            month_["students_p"] += i.user.count()
            month_["plan"] += 1

    for i in Lesson_note.objects.all():
        if i.start.date() == now.date():
            today["students_a"] += i.user.count()
            today["already"] += 1
        if i.start >= monday and i.start <= sunday:
            week["students_a"] += i.user.count()
            week["already"] += 1
        if i.start.year == now.year and i.start.month == now.month:
            month_["students_a"] += i.user.count()
            month_["already"] += 1

    notes = Lesson_note.objects.all()
    if notes:
        notes_dict = {i.id: i for i in notes}
        notes = notes_dict.values()
        notes = sorted(notes, key=lambda x: (x.start))  # 按上课时间排序
        notes = [
            i
            for i in notes
            if timezone.localtime(i.start) + datetime.timedelta(60)
            > timezone.localtime()  # 显示近60天上的课
        ]
        notes = notes[::-1]
        for i in range(len(notes)):
            notes[i].new_id = i + 1
            notes[i].stu_names = "<br>".join(
                [str(i.real_name) for i in notes[i].user.all()])

    context['today'] = today
    context['week'] = week
    context['month'] = month_
    context['notes'] = notes

    return render(request, "home/dashboard.html", context)


def favicon(request):
    """
    处理图标
    """
    return HttpResponseRedirect("/static/home/favicon.ico")


def register(request):
    """
    注册
    """
    context = user_check(request)
    context["title"] += "-注册"
    if request.method == "POST":
        username = request.POST.get("username")
        password = request.POST.get("password")
        re_password = request.POST.get("re_password")
        invite_code = request.POST.get("invite_code")
        if password != re_password:
            context["message_danger"] = "两次输入密码不一致，请检查后输入。"
        elif invite_code not in settings.INVITE_CODE:
            context["message_danger"] = "邀请码错误，请检查后输入。"
        # username, email=None, password=None, **extra_fields
        else:
            try:
                user = User.objects.create_user(
                    username=username, password=password)
                user.save()
                myuser = MyUser.objects.create(user=user)
                myuser.save()
                if user:
                    auth.login(request, user)
                    return index(request, {"message_success": "注册成功。"})
            except:
                context["message_danger"] = "用户已存在，请检查用户名再注册。"
    return render(request, "home/register.html", context)


def login(request):
    """
    处理用户登陆
    """
    context = user_check(request)
    context["title"] += "-登陆"
    if request.user.is_authenticated:
        context["message_danger"] = "请勿重复登陆。"
    elif request.method == "POST":
        username = request.POST.get("username")
        password = request.POST.get("password")
        user = User.objects.filter(username=username)
        if user:
            if not user[0].is_active:
                context["message_danger"] = f"【{username}】用户已被禁用。"
            else:
                user = auth.authenticate(username=username, password=password)
                if user:
                    auth.login(request, user)
                    next_url = request.GET.get('next')
                    if next_url:
                        return redirect(next_url, message_success="登陆成功。")
                    else:
                        return redirect('/')
                else:
                    context["message_danger"] = "登陆失败，请检查用户名和密码。"
        else:
            context["message_danger"] = f"【{username}】用户不存在。"
    return render(request, "home/login.html", context)


def logout(request):
    """
    退出登陆
    """
    user_check(request)
    if request.user.is_authenticated:
        auth.logout(request)
    return index(request, {"message_success": "退出登陆成功。"})  # 退出后，页面跳转至登录界面


def get_notes(myuser: MyUser, n: int = 10):
    """根据用户名获取课程预告和课堂记录"""
    # 如果是教师就10倍展示
    if myuser.user_type == "teacher":
        n *= 10
    # 找到近期课程预告
    notices = Scheduling.objects.filter(Q(user=myuser) | Q(teacher=myuser))
    if notices:
        notices_dict = {i.id: i for i in notices}
        notices = notices_dict.values()
        notices = sorted(
            notices, key=lambda x: (x.start, x.status, x.teacher)
        )  # 按上课时间正序

        # 最多显示过去7天
        notices = [
            i
            for i in notices
            if timezone.localtime(i.start) + datetime.timedelta(1)
            > timezone.localtime()
        ]
        notices = list(notices)[-n:]  # 只显示最近n次内容
        for i in range(len(notices)):
            notices[i].new_id = i + 1

    # 找到最近上的课程
    notes = Lesson_note.objects.filter(Q(user=myuser) | Q(teacher=myuser))
    if notes:
        notes_dict = {i.id: i for i in notes}
        notes = notes_dict.values()
        notes = sorted(notes, key=lambda x: (x.start, x.teacher))  # 按上课时间排序
        notes = [
            i
            for i in notes
            if timezone.localtime(i.start) + datetime.timedelta(60)
            > timezone.localtime()  # 显示近60天上的课
        ]
        notes = list(notes)[-n:]  # 只显示近n次课内容
        notes = notes[::-1]
        for i in range(len(notes)):
            notes[i].new_id = i + 1
            notes[i].stu_names = "<br>".join(
                [str(i.real_name) for i in notes[i].user.all()])
    return notices, notes


def userhome(request):
    """
    用户中心
    """
    context = user_check(request)
    if request.user.is_authenticated:
        context["title"] += "-个人中心"
        myuser = MyUser.objects.filter(user=request.user)  # 找到用户
        if myuser:
            myuser = myuser[0]
            notices, notes = get_notes(myuser)
            if notices:
                context["notices"] = notices
            if notes:
                context["notes"] = notes
        return render(request, "home/userhome.html", context)
    else:
        context["message_danger"] = "请先登录"
        return render(request, "home/login.html", context)


def useradmin(request):
    """
    用户管理中心
    """
    context = user_check(request)
    if request.user.is_authenticated:
        context["title"] += "-管理资料"
        if request.method == "GET":
            return render(request, "home/useradmin.html", context)
        elif request.method == "POST":
            first_name = request.POST.get("first_name")
            last_name = request.POST.get("last_name")
            age = request.POST.get("age")
            gender = request.POST.get("gender")
            if gender not in ["male", "female", "null"]:
                gender = "null"
            avatar = request.POST.get("avatar")
            signature = request.POST.get("signature")
            myuser = context["myuser"]
            if len(last_name) or len(first_name):
                myuser.real_name = last_name + first_name
            myuser.age = age
            myuser.gender = gender
            myuser.avatar = avatar
            myuser.signature = signature
            myuser.save()
            if len(first_name):
                myuser.user.first_name = first_name
            if len(last_name):
                myuser.user.last_name = last_name
            myuser.user.save()
            context["message_success"] = "资料更新成功"
            return render(request, "home/userhome.html", context)

    else:
        context["message_danger"] = "请先登录"
        return render(request, "home/login.html", context)

# @csrf_exempt
# @login_required


def editor(request):
    #     """素材管理"""
    #     form = CreateBugForm()

    #     # 生成的markdown 编辑器的源码：
    #     #logger.highlight(form)
    #     # 生成的markdown 编辑器的文件依赖
    #     #logger.wa(form.media)

    #     # 这里可以看到 生成的完整的 markdown 源代码，然后在下面通过  return render（）将网页源码传到 html 中进行展示
    #     result = {"form": form}
    return render(request, 'ruleroam/bugcreate.html')


def all_notes(request):
    # 找到最近上的课程
    notes = Lesson_note.objects.all()
    if notes:
        notes_dict = {i.id: i for i in notes}
        notes = notes_dict.values()
        notes = sorted(notes, key=lambda x: (x.start))  # 按上课时间排序
        notes = [
            i
            for i in notes
            if timezone.localtime(i.start) + datetime.timedelta(60)
            > timezone.localtime()  # 显示近60天上的课
        ]
        notes = notes[::-1]
        for i in range(len(notes)):
            notes[i].new_id = i + 1
            notes[i].stu_names = "<br>".join(
                [str(i.real_name) for i in notes[i].user.all()])
    return render(request, "home/notes.html", {"notes": notes})
